import { observable, action, toJS } from 'mobx';
import { Reply,Form,CKRichText, Browser, BrowserHrm } from 'weaver-mobile-page';
import { Tools, Bubble, Toast,Modal } from 'weaver-mobile';
import { Base64 } from 'js-base64'
import * as Api from '../../apis/new';
import { doConfirm, regEmail } from '../../util';
import {convertToEmail} from '../../components/widget/MailInput';
const getLabel = Tools.getLabel;
const CKRichEditor = CKRichText.CKRichEditor;
const { alert } = Modal;
export default class NewStore {
  
  path;
  replyRef;
  @observable params;
  @observable replyStore = new Reply.Store({ getAttachList: this.getReplyAttachList});
  @observable ckStore = new CKRichEditor.Store({ initEndCallback: this.registerRichEditor });
  @observable outerInputBrowserStore;
  @observable innerInputBrowserStore;
  @observable outerInputDomkey;// 收件人资源框对应的domKey
  @observable outerInputValueArray;
  @observable innerInputValueArray;
  @observable content;
  @observable config;
  @observable mailTypes = [];// 邮件类型，内部邮件/外部邮件
  // 用于记录mailType是否在变化。变化时会将下方的form表单设为空，以保证动画的流畅性
	@observable mailTypeIsChanging = false;
	/*
	* 用于记录mailType变化是否结束。结束后会卸载QueueAnim组件。设为true后马上会重新设为false。
	* 用于解决部分环境下不卸载QueueAnim直接复用会报错的问题
	* */
	@observable mailTypeChangeEnd = false;
  @observable mailTypesSelected = 0;
  @observable innerForm;
  @observable outerForm;
  @observable elliVisible = false;
  @observable elliStatus = {
    cc: false,
    bcc: false,
    separate: false,
  }
  initPromise = null;
  @observable sendEndStatus = null;
  @observable signList = []; // 签名
  @observable templateList = []; // 模板
  @observable timingdate = '';
  
  @observable replyFileList = [];

  @observable viewLog = false;
  @observable hasOverflow = true;//是否禁用滚动条

  @observable email_sendsessionUUid = "";

  @observable continueWrite = false;

  @observable remainspace = 0;

  @observable curHumanId = ''; // 当前发件人ID
  @observable classification = {}; // 存储发件人对应密级

  @observable autoSave = 0;
  @observable autofrequency = 1000 * 60;
  @observable autoLoading = false;
  
  @action
  setState = (params = {}, callback) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });
    if (callback && typeof callback === 'function') callback();
    return this;
  }

// 创建form表单配置
  createFormFields = (isInternal) => {
    const form = isInternal ? this.innerForm : this.outerForm;
    const config = toJS(this.config);
    // 生成单行配置的方法
    const createField = (conditionType, key, label, params) => {
      let field = {
        colSpan: 1,
        conditionType,
        domkey: [key],
        label,
        viewAttr: 2,
        onChange: (...args) => {
          form.onChange.apply(this, args);
        },
        ...params
      };
      if (field.viewAttr === 3 && !field.rules) {
        field.rules = 'required';
      }
      return field;
    }
    // 生成单行必填配置的方法
    const createRequiredField = (conditionType, key, label, params) => createField(conditionType, key, label, {...params, viewAttr: 3});
    // 创建下拉选择配置的方法，增加了如果只有一条则默认选中且不可选择的逻辑。
    const createSelectedField = (options, key, label, params) => {
      let newParams;
      if (!Array.isArray(options) || options.length <= 1) {
        let newOptions = [];
        let viewAttr = 1;
        if (Array.isArray(options) && options.length === 1) {
          newOptions.push({...options[0], selected: true});
          // 空选项判断，处理空发件人显示必填问题
          if (!options[0].key) { viewAttr = 3; }
        }
        newParams = { ...params, options: newOptions, viewAttr};
      } else {
        newParams = { ...params, options: options};
      }
      return createField('SELECT', key, label, newParams);
    }
    
    // 创建配置
    const fields = [], {sendFrom_internal, sendFrom_outer} = config;
    if (isInternal) {
      // 内部邮件发件人
      let sendFromArr = sendFrom_internal.filter(v => v.selected);
      if (sendFromArr.length === 0) {
        sendFrom_internal[0] = { ...sendFrom_internal[0], selected: true };
        this.curHumanId = sendFrom_internal[0].key;
      } else {
        this.curHumanId = sendFromArr[0].key;
        if(sendFrom_internal.length>1){
          sendFrom_internal.map(v =>{
            if(v.masterAccount){
                v.showname = v.showname + " (主)";
              
              }else{
                v.showname = v.showname + " (次)";
              }
            }
          );
        }
      }
      fields.push(createSelectedField(sendFrom_internal, 'hrmAccountid', getLabel('2034', '发件人'), {viewAttr: 3}));
      const hrmConditionParam = {
        browserConditionParam: {
          type: 17,
          isSingle: false,
          isShowGroup :true
        },
      };
      fields.push(createRequiredField('BROWSER', 'internaltonew', getLabel(2046, '收件人'), hrmConditionParam));
      fields.push(createField('BROWSER', 'internalccnew', getLabel(2084, '抄送'),
        {
          ...hrmConditionParam,
          hide: () => !this.elliStatus.cc || this.elliStatus.separate
        }));
      fields.push(createField('BROWSER', 'internalbccnew', getLabel(2085, '密送'),
        {
          ...hrmConditionParam,
          hide: () => !this.elliStatus.bcc || this.elliStatus.separate
        }));
    } else {
      // 外部邮件发件人
      fields.push(createSelectedField(sendFrom_outer, 'mailAccountId', getLabel('2034', '发件人'), {viewAttr: 3}));
      /*fields.push(createRequiredField('INPUT', 'to', getLabel(-1, '收件人'),));
      fields.push(createField('INPUT', 'cc', getLabel(-1, '抄送'),
        {
          hide: () => !this.elliStatus.cc || this.elliStatus.separate
        }));
      fields.push(createField('INPUT', 'bcc', getLabel(-1, '密送'),
        {
          hide: () => !this.elliStatus.bcc || this.elliStatus.separate
        }));*/
      fields.push(createRequiredField('MailInput', 'to', getLabel(2046, '收件人'), ));
      fields.push(createField('MailInput', 'cc', getLabel(2084, '抄送'),
        {
          hide: () => !this.elliStatus.cc || this.elliStatus.separate,
        }));
      fields.push(createField('MailInput', 'bcc', getLabel(2085, '密送'),
        {
          hide: () => !this.elliStatus.bcc || this.elliStatus.separate,
        }));
    }
    
    // 保持内部邮件与外部邮件一致的onChange方法
    const identicalChange = (...args) => {
      this.innerForm.onChange.apply(this, args);
      this.outerForm.onChange.apply(this, args);
    }
    const priorityOptions = [{ showname: getLabel(2086, '普通'), key: '3', selected: true }, { showname: getLabel(28090, '紧急'), key: '1', selected: false }];
    fields.push(createSelectedField(priorityOptions, 'priority', getLabel(848, '重要性'), {onChange: identicalChange}));
    fields.push(createRequiredField('INPUT', 'subject', getLabel(344, '主题'), {onChange: identicalChange, otherParams: {maxLength: 300}}));
    if (isInternal && JSON.stringify(toJS(this.config.resourceClassification)) !== "{}") {
      for (let item in toJS(this.config.resourceClassification)) {
        if (!this.classification[item]) {
          let selectedItem = toJS(this.config.resourceClassification)[item].filter(v => v.selected);
          let selectedKey = selectedItem.length > 0 ? selectedItem[0].key : ''
          this.classification[item] = selectedKey;
        }
      }
      let others = [1, 2, 3, 5, 6, 7];
      let params = !others.includes(this.config.flag) ? {viewAttr: 3} : {viewAttr: 1}
      fields.push(createSelectedField(toJS(this.config.resourceClassification)[this.curHumanId], 'classification', getLabel('500520','密级'), params));
    }
    return fields;
  }
  
  /**
   * 初始化方法
   * @param path
   * @param params
   * @returns {PromiseLike<T> | Promise<T> | *}
   */
  init = (path, params, callback) => {
    this.replyStore.doClear();
    this.ckStore.setData('');
    this.params = params;
    this.path = path;
    this.classification = {};
    this.innerForm = new Form.Store({route: path});
    this.outerForm = new Form.Store({route: path});
    this.outerInputBrowserStore = new Browser.Store({route: path});
    this.innerInputBrowserStore = new BrowserHrm.Store({route: path});
    this.elliVisible = false;
    Toast.loading('',0)
    // 防并发处理
    const getConfig = () => {
      return Api.emailAdd(toJS(this.params)).then((result) => {
        if (!result.emailAddBean) {
          Toast.hide();
          Bubble.error(result.api_errormsg);
          return;
        }
        const {emailAddBean} = result, {content, innerMail, outerMail, isInternal, autoSave, saveInterval} = emailAddBean;
        this.email_sendsessionUUid = result.email_sendsessionUUid&&result.email_sendsessionUUid;
        this.content = Base64.decode(content);
        this.ckStore.setData(this.content);
        // 处理内部邮件、外部邮件
        let mailTypes = [];
        if (innerMail === 1) {
          mailTypes.push({
            id: 'inner',
            value: getLabel('24714', '内部邮件')
          });
        }
        if (outerMail === 1) {
          mailTypes.push({
            id: 'outer',
            value: getLabel('31139', '外部邮件')
          });
        }
        this.mailTypes = mailTypes;
        this.mailTypesSelected = isInternal || mailTypes.length < 2 ? 0 : 1;

        this.config = emailAddBean;
        this.innerForm && this.innerForm.initForm([{defaultshow: true, items: this.createFormFields(true), show: true}], path);
        this.outerForm && this.outerForm.initForm([{defaultshow: true, items: this.createFormFields(false), show: true}], path);
        // form表单写入
        const { subject,
          sendTo_internal, sendBcc_internal,sendCc_internal,
          sendTo_outer, sendBcc_outer,sendCc_outer} = emailAddBean;
        let priority = emailAddBean.priority === 1 ? '1' : '3';//除了1是紧急，其它都计作普通
        this.innerForm && this.innerForm.updateFields({
          subject:{value: subject},
          priority:{value: priority},
          internaltonew: {value: sendTo_internal},
          internalccnew: {value: sendCc_internal},
          internalbccnew: {value: sendBcc_internal},
        });
        this.outerForm && this.outerForm.updateFields({
          subject:{value: subject},
          priority:{value: priority},
          to: {value: convertToEmail(sendTo_outer)},
          cc: {value: convertToEmail(sendCc_outer)},
          bcc: {value: convertToEmail(sendBcc_outer)},
        });

        const {timingdate} = emailAddBean;
        this.timingdate = timingdate;
        // 抄送、密送、分别发送
        const {op_isShowSendBcc, op_isShowSendCc, isSendApart} = emailAddBean;
        this.elliStatus = {
          cc: !!op_isShowSendCc,
          bcc: !!op_isShowSendBcc,
          separate: !!isSendApart,
        };
        // 附件列表
        let fileList = this.config && this.config.fileInfos && toJS(this.config.fileInfos.fileList);
        this.replyFileList = (fileList || []).map((item) => ({id: item.fileid, ...item}));
        this.replyStore.doInit();
        Toast.hide();

        // 定时保存草稿
        this.autoSave = autoSave;
        this.autofrequency = saveInterval * 60 * 1000;

        // 回调
        if (callback && typeof callback === 'function') callback();
      });
    }
    if (this.initPromise) {
      this.initPromise = this.initPromise.then(() => {
        return getConfig()
      });
    } else {
      this.initPromise = getConfig();
    }
    return this.initPromise;
  }
  /**
   * 修改内部邮件还是外部邮件
   * @param index
   */
  changeMailType = (index) => {
    this.mailTypeIsChanging = true;
    this.mailTypesSelected = index;
    this.replyStore.doInit();
    // const conditions = [{defaultshow: true, items: createFormFields(toJS(this.config), this.isInternal()), show: true}];
    // this.form.resetConditions(conditions, this.path);
  }

  @action
  filterRerson = (params) => {
    let internaltonewIds = "";
    let internalccnewIds = "";
    let internalbccnewIds = "";
    const dealInternalData = (formData,type) => {
      return toJS(formData.value).map((item) => {
        if (item.type === 'allResource') {
          return {id: 'all', type: 'all'}
        } else {
          if("to" === type){
            internaltonewIds = internaltonewIds + "," + (item.users ? item.users.map(obj => obj.id).join(",") : item.id);
          }else if("cc" === type){
            internalccnewIds = internalccnewIds + "," + (item.users ? item.users.map(obj => obj.id).join(",") : item.id);
          }else if("bcc" === type){
            internalbccnewIds = internalbccnewIds + "," + (item.users ? item.users.map(obj => obj.id).join(",") : item.id);
          }
          return {
            id: item.id, 
            type: item.type, 
            userids: item.users?item.users.map(obj => obj.id).join(","):item.id,
          };
        }
      })
    }
    params = {
      internaltonew: JSON.stringify(dealInternalData(this.innerForm.formData.internaltonew,"to")),
      internalccnew: JSON.stringify(dealInternalData(this.innerForm.formData.internalccnew,"cc")),
      internalbccnew: JSON.stringify(dealInternalData(this.innerForm.formData.internalbccnew,"bcc")),
      hrmAccountid: this.innerForm.formData.hrmAccountid.value,
      ...params
    };
    Api.filterRerson(params).then(res => {
      this.innerForm.updateFields({
        internaltonew: {value: res.sendTo_internal},
        internalccnew: {value: res.sendCc_internal},
        internalbccnew: {value: res.sendBcc_internal},
      })
    })
  }
  
  isInternal = () => {
    if (this.mailTypes.length > 0) {
      return this.mailTypes[this.mailTypesSelected].id === 'inner';
    }
    return true;
  }
  /**
   * 返回 回复表情组件的更多设置
   * @returns {Promise<any>}
   */
  getReplyAttachList = () => {
    let {fileUploadConfig = {}, editerApps_internal = [], editerApps_outer = [],uploadTypeWhiteAuth} = this.config || {},
      {attachmentCount, perAttachmentSize, totalAttachmentSize,openUploadType,uploadTypeRestriction} = fileUploadConfig;
    // editerApps_internal = editerApps_internal.filter(v => v.type !== 'emailTemplate' && v.type !== 'emailSign');
    // editerApps_outer = editerApps_outer.filter(v => v.type !== 'emailTemplate' && v.type !== 'emailSign');
    const appToReplyAttach = (item) => {
      if (item.name === 'Browser') {
        return {
          key: item.type,
          type: 'browser',
          config: {
            type: item.type,
            isSingle: false,
            hasAdvanceSerach: true,
          },
          path: this.path,
          iconType: item.icon,
          iconBgColor: item.iconBgColor,
          text: item.title,
          model: 2,
        };
      } 
      if (item.name === 'Picker') {
        let data = []
        if (item.pickerArray && item.pickerArray !== null && item.pickerArray.length > 0) {
          data = item.pickerArray.map((v, index) => {
            return {
              value: index,
              label: v.showname,
							content: v.content,
							subject: v.subject,
							title: v.title,
            }
          });
          if (item.type === 'emailSign') {
            this.signList = data;
          }
          if (item.type === 'emailTemplate') {
            this.templateList = data;
          }
        }
        return {
          key: item.type,
          type: 'picker',
          config: {
            data,
            cols: 1,
          },
          iconType: item.icon,
          iconBgColor: item.iconBgColor,
          text: item.title,
          model: 2,
        };
      }
    }
    let attachList = [];
    attachList.push(
      {
        key: 'upload',
        type: 'upload',
        path: `${this.path}/upload`,
        config: {
          multiSelection: true,
          limitType: '',
          maxUploadSize: perAttachmentSize,
          maxFilesNumber: attachmentCount,
          totalMaxUploadSize: totalAttachmentSize,
          uploadUrl: '/api/email/add/uploadFile',
          datas: toJS(this.replyFileList),
          prohibitType : ((openUploadType === 1 || openUploadType === "1")&& uploadTypeWhiteAuth !="1")?uploadTypeRestriction:""
        },
        iconType: 'enclosure',
        iconBgColor: '#57D58F',
        text: getLabel(156, '附件'),
        model: 1
      }
    );
    if (this.isInternal()) {
      let tempAttach = toJS(editerApps_internal).map(appToReplyAttach);
      attachList = [...attachList, ...tempAttach];
    } else {
      let tempAttach = toJS(editerApps_outer).map(appToReplyAttach)
      attachList = [...attachList, ...tempAttach];
    }
    return new Promise(resolve => resolve({attachList}));
  }
  
  //  以下都是调用insertHTML方法，插入需要的html数据 (具体要什么样的html自定义)
  onEmojiChange = emoji => this.insertHtml(`<span>${emoji}</span>`);

  onImgChange = (datas) => {
    datas.forEach(v => this.insertHtml(`<img src=${v.filelink} />`));
  }

  onAtChange = (datas) => {
    datas.forEach(v => this.insertHtml(`<a id=${v.id}>${v.name}</a>&nbsp;&nbsp;&nbsp;`));
  }

  onBrowserChange = (key, datas) => {
    const mirror = {
      37: 'doc',
      prjtsk: 'prjtsk',
      18: 'crm',
      152: 'workflow',
      8: 'project',
      workplan: 'workplan',
      blogTemplate: 'blogTemplate',
    };
    const url = {
      doc: '/spa/document/static4mobile/index.html#/doc/',
      workflow: '/spa/workflow/forwardMobileForm.html?requestid=',
      project: '/spa/prj/static4mobile/index.html#/ProjectDetails/0/',
      prjtsk: '/spa/prj/static4mobile/index.html#/TaskDetails/0/',
      crm: '/spa/crm/static4mobile/index.html#/customerCard/',
      workplan: '/spa/workplan/static4mobile/index.html#/detail?workplanId=',
    };
    datas.forEach(item => this.insertHtml(
      `<a linkid='${item.id}' linkType='${key}' href='${url[mirror[key]]}${item.id}'`
      + "target='_blank' ondblclick='return false;'  unselectable='off' contenteditable='false'"
      + "style='cursor:pointer;text-decoration:underline !important;margin-right:8px'"
      + `>${item.name || item.showname}</a>&nbsp;`));
  }
  
  onUploadChange = (key, datas) => this.replyFileList = datas;
  
  onSpeechChange = datas => this.insertHtml(`<span>${datas}</span>`);

  onPickerChange = (key, value) => {
    if (key === 'emailSign') { // 签名
      const curParams = this.signList[value[0]];
      this.insertHtml(curParams.content);
    }
    if (key === 'emailTemplate') { // 模板
      doConfirm(getLabel(384366,'使用模板会覆盖当前内容，确认覆盖？'), '', () => {
				const form = this.isInternal() ? this.innerForm : this.outerForm;
				const curParams = this.templateList[value[0]];
        this.ckStore.setData(curParams.content);
        this.ckStore.focus('last'); // 获取焦点
        form.updateField('subject', curParams.subject);
      });
    }
  }

  insertHtml = (...args) => {
    this.ckStore.insertHtml(...args);
  }

  setReplyRef = (ref) => {
    this.replyRef = ref;
  }

  formatDate = (time, str) => {
    let obj = {
      yyyy: time.getFullYear(),
      MM: ('0' + (time.getMonth() + 1)).slice(-2),
      dd: ('0' + time.getDate()).slice(-2),
      HH: ('0' + time.getHours()).slice(-2),
      mm: ('0' + time.getMinutes()).slice(-2),
    }
    return str.replace(/([a-z]+)/ig, v => obj[v])
  }

  getTime = (now, time) => {
    let a = now.replace(/-/g,'').replace(' ','').replace(':','');
    let b = time.replace(/-/g,'').replace(' ','').replace(':','');
    return a*1 - b*1
  }
  
  sendEmail = ({isDraft, history, isFromWf, autoSave} = {isDraft: false, isFromWf: false, autoSave: false}) => {
    if (this.curHumanId !="1" && parseFloat(this.remainspace) <= parseFloat(0)) {
      //管理员不做空间限制
      alert(getLabel('83075', '个人可用空间已满，请删除部分邮件后再进行发送'), '', [
        { text: getLabel('31129', '取消') },
        { text: getLabel('826', '确定') },
      ]);
      return;
    }

    if (this.timingdate !== '') {
      let nowTime = this.formatDate(new Date, 'yyyy-MM-dd HH:mm');
      let timeDate = this.getTime(nowTime, this.timingdate);
      if (timeDate > 0) {
        Bubble.error(getLabel('517429', '定时发送时间不能晚于当前时间'));
        return;
      }
    }

    return new Promise((resolve) => {
      if (isDraft) {
        resolve();
      } else {
        const isInternal = this.isInternal();
        const form = isInternal ? this.innerForm : this.outerForm;
        let validResult = form.doValidate();
        if (validResult.pass) {
          if (!isInternal) { // 外部邮件收件人邮箱校验
            let regToSpan = regEmail(toJS(form.formParams.to));
            let regCcSpan = toJS(form.formParams.cc) !== '' ? regEmail(toJS(form.formParams.cc)) : true;
            let regBccSpan = toJS(form.formParams.bcc) !== '' ? regEmail(toJS(form.formParams.bcc)) : true;
            if (!regToSpan || !regCcSpan || !regBccSpan) {
              Bubble.error(getLabel(508417, '请填写正确的邮箱地址'));
            } else {
              resolve();
            }
          } else {
            resolve();
          }
        } else {
          Bubble.error(validResult.message);
        }
      }
    }).then(() => {// todo
      const isInternal = this.isInternal();
      const form = isInternal ? this.innerForm : this.outerForm;
      const { flag, savesend = 1, texttype = 0, needReceipt = 0, mailId="" } = this.config;
      let params = {
        ...toJS(form.formParams),
        isInternal: isInternal ? 1 : 0,
        mouldtext: Number(texttype) === 1 ? toJS(this.content) : this.ckStore.getData(),
        flag,
        texttype,
        needReceipt,
        savedraft: isDraft ? 1 : 0,
        isSendApart: this.elliStatus.separate ? 1 : 0,
        op_isTimingSend: this.timingdate !== '' ? 1 : 0,
        savesend: this.timingdate !== '' ? 1 : savesend,
        timingdate: this.timingdate,
        mailid: this.params ? this.params.id : '',
        oldmailid:mailId,
        sessionUUid:this.email_sendsessionUUid,
      };
      if (params.subject && params.subject.length > 300) {
        Bubble.error(getLabel('520157','请填写正确的邮件主题'));
        return;
      }
      if (this.params) {
        if ((!this.params.isSend || (this.params.isSend && this.params.isSend !== 'draftSaved')) && (flag === 1 || flag === 2 || flag === 3 || flag === 5 || flag === 6 || flag === 7)){
          params.mailid = '';
        }
      }
      const upload = toJS(this.replyFileList);
      if (upload.length > 0) {
        params.hasfile = 1;
        params.accids = upload.map((item) => item.id).join();
      }
      if (isInternal) {
        // 处理数据与所有人的逻辑
        let internaltonewIds = "";
        let internalccnewIds = "";
        let internalbccnewIds = "";
        
        const dealInternalData = (formData,type) => {
          return toJS(formData.value).map((item) => {
            if (item.type === 'allResource') {
              return {id: 'all', type: 'all'}
            } else {
              if("to" === type){
                internaltonewIds = internaltonewIds + "," + (item.users ? item.users.map(obj => obj.id).join(",") : item.id);
              }else if("cc" === type){
                internalccnewIds = internalccnewIds + "," + (item.users ? item.users.map(obj => obj.id).join(",") : item.id);
              }else if("bcc" === type){
                internalbccnewIds = internalbccnewIds + "," + (item.users ? item.users.map(obj => obj.id).join(",") : item.id);
              }
              return {
                id: item.id, 
                type: item.type, 
                userids: item.users?item.users.map(obj => obj.id).join(","):item.id,
              };
            }
          })
        }
        params.internaltonew = JSON.stringify(dealInternalData(form.formData.internaltonew,"to"));
        params.internalccnew = JSON.stringify(dealInternalData(form.formData.internalccnew,"cc"));
        params.internalbccnew = JSON.stringify(dealInternalData(form.formData.internalbccnew,"bcc"));
        params.internaltonewIds = internaltonewIds;
        params.internalccnewIds = internalccnewIds;
        params.internalbccnewIds = internalbccnewIds;
        params.usernameTo = JSON.stringify([]);
        params.usernameCc = JSON.stringify([]);
        params.usernameBcc = JSON.stringify([]);
      } else {
        params.to = form.formData.to.value.map((item) => item.id).join();
        params.cc = form.formData.cc.value.map((item) => item.id).join();
        params.bcc = form.formData.bcc.value.map((item) => item.id).join();
        params.usernameTo = JSON.stringify(form.formData.to.value.map(v => (this.getNameAndAddress(v.name))));
        params.usernameCc = JSON.stringify(form.formData.cc.value.map(v => (this.getNameAndAddress(v.name))));
        params.usernameBcc = JSON.stringify(form.formData.bcc.value.map(v => (this.getNameAndAddress(v.name))));
      }
      !autoSave ? Toast.loading('',0) : (this.autoLoading = true);
      Api.sendEmail(params).then((res) => {
        Toast.hide();
        this.autoLoading = false
        this.sendEndStatus = res;
        this.sendEndStatus.isDraft = isDraft;
        if (isDraft) {
          const {status, isSend} = res;
          let sendSuccess = status === '1' && (isSend === 'true' || isSend === 'draftSaved');
          if (sendSuccess) {
            Bubble.success(getLabel(384403, '保存草稿成功'));
            this.params = this.params ? {...toJS(this.params), id: res.mailId, isSend: res.isSend} : {id: res.mailId, isSend: res.isSend};
            this.replyFileList = res.fileInfos.fileList || [];
          } else  {
            Bubble.error(`${getLabel(71, '邮件')}${getLabel(30986, '保存')}${getLabel(84566, '失败！')}`);
          }
        } else {
          history && history.push({
            pathname: `${this.path}/end`,
            state: { isFromWf }
          });
        }
      }).catch(() => {
        Toast.hide()
        this.autoLoading = false
      });
    })
  }

  getNameAndAddress = (value) => {
    let address = value.match(/<(.*?)>/g);
    address = (address && address.length > 0) ? address[address.length - 1].replace(/[<>\s]/g, '').trim() : value;
    let username = value.match(/^.*</);
    username = username ? username[0].replace(/<$/, '').trim() : '';
    return {
      mailusername: username,
      mailaddress: address
    };
  }
  
  registerRichEditor = () => {
    const { editor } = this.ckStore;
    editor.on('focus', () => {
      this.hideReply();
    }); // onFocus时关闭reply组件
    this.ckStore.focus('first'); // 获取焦点
  }
  
  hideReply = () => {
    // this.replyRef && this.replyRef.setVisible(false);
    this.replyStore.setState({ activeKey: '' });
  }
  
  selectNewElli = (item,index) =>{
    this.elliVisible = false;
    this.elliStatus[item.key] = !this.elliStatus[item.key];
    if (this.elliStatus.separate) {
      let {internaltonew, internalccnew, internalbccnew} = toJS(this.innerForm.formData);
      let map = {};
      let newValue = [...internaltonew.value, ...internalccnew.value, ...internalbccnew.value].filter((item) => {
        let key =  item.type+'_'+item.id;
        if (map[key]) {
          return false;
        }
        map[key] = true;
        return true;
      });
      this.innerForm.updateField('internaltonew', newValue);
      this.innerForm.updateField('internalccnew', []);
      this.innerForm.updateField('internalbccnew', []);
      let {to, cc, bcc} = toJS(this.outerForm.formData);
      map = {};
      let outerValue = [...to.value, ...cc.value, ...bcc.value].filter((item) => {
        if (map[item.id]) {
          return false;
        }
        map[item.id] = true;
        return true;
      })
      this.outerForm.updateField('to', outerValue);
      this.outerForm.updateField('cc', []);
      this.outerForm.updateField('bcc', []);
    }
  }

  @action
  filterOutEmail = async (params) => {
    let res = await Api.filterOutEmail(params)
    return res;
  }
  
  clear = (callback) => {
    this.init(this.path, {}, callback);
  }
  clearState = () => {
    this.content = '';
    this.mailTypes = [];
    this.mailTypeChangeEnd = false;
    this.mailTypesSelected = 0;
    this.innerForm = null;
    this.outerForm = null;
    this.elliVisible = false;
    this.elliStatus = {
      cc: false,
      bcc: false,
      separate: false,
    }
    this.initPromise = null;
    this.sendEndStatus = null;
    this.signList = []; // 签名
    this.templateList = []; // 模板
    this.timingdate = '';
    
    this.replyFileList = [];

    this.viewLog = false;
    this.hasOverflow = true;//是否禁用滚动条

    this.email_sendsessionUUid = "";

    this.continueWrite = false;

    this.classification = {};
  }
}
